import React, { useEffect, useState } from "react";
import { NavBar, Button, Dialog, Toast } from "antd-mobile";
import { useLocation, useNavigate } from "react-router-dom"
import { useDispatch, useSelector } from 'react-redux';
import { addWrongQuestion, selectWrongQuestions } from '../../store/wrong';
import { addCollectedQuestion, removeCollectedQuestion, selectCollectedQuestions } from '../../store/collect';
import { StarOutline, StarFill } from 'antd-mobile-icons'
import useTimer from '../../hooks/useTimer';
import axios from "./axios";
import styles from "./Practice.module.css"
import store from '../../store';

export default function Practice() {
    const navigate = useNavigate()
    const location = useLocation()
    const dispatch = useDispatch()
    const wrongQuestions = useSelector(selectWrongQuestions);
    const collectedQuestions = useSelector(selectCollectedQuestions);
    const { course, page } = location.state
    const [list, setList] = useState([])
    const [current, setCurrent] = useState(1)
    const pageSize = 1
    const [total, setTotal] = useState(0)
    const [selectedOption, setSelectedOption] = useState(null)
    const [showAnswer, setShowAnswer] = useState(false)
    const [isCorrect, setIsCorrect] = useState(false)
    const [isCollected, setIsCollected] = useState(false);

    // 使用计时器
    const { time, startTimer, stopTimer, formatTime } = useTimer();

    useEffect(() => {
        getData();
        // 进入页面时启动计时器
        startTimer();

        // 离开页面时停止计时器并保存时间
        return () => {
            stopTimer();
            const currentTime = parseInt(localStorage.getItem('practiceTime')) || 0;
            if (currentTime > 0) {
                const courseKey = `practice_time_${course}`;
                const previousTime = parseInt(localStorage.getItem(courseKey)) || 0;
                // 确保时间至少为1分钟（60秒）
                const timeToSave = Math.max(60, currentTime + previousTime);
                localStorage.setItem(courseKey, timeToSave.toString());
                // 清除临时计时
                localStorage.removeItem('practiceTime');
            }
        };
    }, [course, startTimer, stopTimer]); // 添加所有必要的依赖项

    // 在组件卸载时也保存时间
    useEffect(() => {
        return () => {
            const currentTime = parseInt(localStorage.getItem('practiceTime')) || 0;
            if (currentTime > 0) {
                const courseKey = `practice_time_${course}`;
                const previousTime = parseInt(localStorage.getItem(courseKey)) || 0;
                const timeToSave = Math.max(60, currentTime + previousTime);
                localStorage.setItem(courseKey, timeToSave.toString());
                localStorage.removeItem('practiceTime');
            }
        };
    }, [course]);

    // 检查当前题目是否已收藏
    useEffect(() => {
        if (list.length > 0) {
            const currentQuestion = list[current - 1];
            setIsCollected(collectedQuestions.some(q => q._id === currentQuestion._id));
        }
    }, [current, list, collectedQuestions]);

    const getData = async () => {
        try {
            const res = await axios.get("/lz/list", { params: { course: course, page: page } })
            console.log('获取到的题目数据：', res.data);
            setList(res.data.data)
            setTotal(res.data.total)
        } catch (error) {
            console.error('获取题目失败：', error);
            Toast.show({
                icon: 'fail',
                content: '获取题目失败'
            });
        }
    }

    // 处理选项选择
    const handleOptionSelect = (option) => {
        if (showAnswer) return;
        setSelectedOption(option);
        console.log('选择的选项：', option);
    };

    // 检查答案并处理下一题
    const handleNext = () => {
        if (showAnswer) {
            // 如果已经显示答案，则进入下一题
            if (current >= list.length) {
                handleComplete();
            } else {
                setCurrent(current + 1);
                setSelectedOption(null);
                setShowAnswer(false);
            }
            return;
        }

        const currentQuestion = list[current - 1];
        const correct = selectedOption === currentQuestion.answer;
        setIsCorrect(correct);
        setShowAnswer(true);

        if (!correct) {
            try {
                // 检查是否已经存在于错题本中
                console.log('当前错题本数据：', wrongQuestions);
                const alreadyExists = wrongQuestions.some(q => q._id === currentQuestion._id);
                console.log('当前题目是否已存在：', alreadyExists);
                if (!alreadyExists) {
                    // 如果答错且不在错题本中，添加到错题本
                    const wrongQuestion = {
                        _id: currentQuestion._id || `${Date.now()}`,
                        title: currentQuestion.title,
                        options: currentQuestion.options || [],
                        answer: currentQuestion.answer,
                        selectedAnswer: selectedOption,
                        course: course
                    };
                    console.log('准备添加到错题本的题目：', wrongQuestion);
                    dispatch(addWrongQuestion(wrongQuestion));
                    console.log('dispatch 操作已执行');
                    
                    // 添加延时检查
                    setTimeout(() => {
                        const currentState = store.getState();
                        console.log('添加后的错题本数据：', currentState.wrong.wrongQuestions);
                    }, 100);

                    Toast.show({
                        icon: 'fail',
                        content: '回答错误，已添加到错题本'
                    });
                } else {
                    Toast.show({
                        icon: 'fail',
                        content: '回答错误'
                    });
                }
            } catch (error) {
                console.error('添加错题失败：', error);
            }
        } else {
            Toast.show({
                icon: 'success',
                content: '回答正确'
            });
        }
    };

    // 处理练习完成
    const handleComplete = () => {
        Dialog.show({
            content: '练习完成！',
            closeOnAction: true,
            actions: [
                {
                    key: 'back',
                    text: '返回练习库',
                    onClick: () => {
                        navigate("/test", { state: { course: course } });
                    }
                },
                {
                    key: 'result',
                    text: '查看练习结果',
                    onClick: () => {
                        navigate("/result", { state: { course: course } });
                    }
                }
            ]
        });
    };

    // 获取选项的类名
    const getOptionClassName = (option) => {
        if (!showAnswer) {
            return `${styles.option} ${selectedOption === option ? styles.selected : ''}`;
        }

        const currentQuestion = list[current - 1];
        if (option === currentQuestion.answer) {
            return `${styles.option} ${styles.correct}`;
        }
        if (option === selectedOption && option !== currentQuestion.answer) {
            return `${styles.option} ${styles.wrong}`;
        }
        return styles.option;
    };

    // 处理收藏/取消收藏
    const handleCollect = () => {
        const currentQuestion = list[current - 1];
        if (isCollected) {
            dispatch(removeCollectedQuestion(currentQuestion._id));
            Toast.show({
                icon: 'success',
                content: '已取消收藏'
            });
        } else {
            dispatch(addCollectedQuestion({
                _id: currentQuestion._id,
                title: currentQuestion.title,
                options: currentQuestion.options,
                answer: currentQuestion.answer,
                course: course
            }));
            Toast.show({
                icon: 'success',
                content: '已加入收藏'
            });
        }
    };

    return (
        <div>
            <NavBar onBack={() => {
                stopTimer(); // 点击返回时停止计时器
                navigate("/test", { state: { course: course } });
            }}>练习</NavBar>
            <div className={styles.timer}>
                学习时长：{formatTime(time).formatted}
            </div>
            <div className={styles.container}>
                {list.slice((current - 1) * pageSize, current * pageSize).map(i => (
                    <div key={i._id} className={styles.questionBox}>
                        <div className={styles.titleRow}>
                            <div className={styles.title}>{current}.{i.title}</div>
                            <div className={styles.collectButton} onClick={handleCollect}>
                                {isCollected ? <StarFill style={{ color: '#FFB74D' }} /> : <StarOutline />}
                            </div>
                        </div>
                        <div className={styles.options}>
                            {i.options.map(j => (
                                <div
                                    key={j.id}
                                    className={getOptionClassName(j.option)}
                                    onClick={() => handleOptionSelect(j.option)}
                                >
                                    {j.option}、{j.content}
                                </div>
                            ))}
                        </div>
                    </div>
                ))}
                <Button
                    color='primary'
                    block
                    onClick={handleNext}
                    disabled={!selectedOption && !showAnswer}
                    className={styles.nextButton}
                >
                    {showAnswer ? (current >= list.length ? '完成' : '下一题') : '确认答案'}
                </Button>
            </div>
        </div>
    )
}